//
//  KDirectoryViewController.m
//  Keping
//
//  Created by 柯平 on 2017/6/30.
//  Copyright © 2017年 柯平. All rights reserved.
//

#import "KDirectoryViewController.h"
#import "HJWebViewController.h"
#import "HJDirectorySubViewController.h"
#import "KDirectoryRequest.h"
#import <SDCycleScrollView.h>
#import "HomeItemCell.h"
#import "KBannersData.h"
#import "KWebViewController.h"
#import "KDirectoryCategoryModel.h"

@interface KDirectoryViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,SDCycleScrollViewDelegate>
{
}
@property(nonatomic,strong)SDCycleScrollView* headView;
@property(nonatomic,strong)UICollectionView* collectionView;
@property (nonatomic, strong) NSMutableArray *items;

@end

@implementation KDirectoryViewController

- (NSMutableArray *)items {
    if (!_items) {
        _items = [[NSMutableArray alloc] init];
    }
    return _items;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"Directory";
    
    self.collectionView.backgroundColor = kWhiteColor;
    [self.collectionView registerClass:[HomeItemCell class] forCellWithReuseIdentifier:[HomeItemCell className]];
    [self getData];
}

-(void)getData
{
    [super getData];
    [self showLoading];
    WEAKSELF
    __block KDirectoryPhotosRequest* request = [[KDirectoryPhotosRequest alloc] init];
    request.params = @{@"type":@"indexBanner"};
    __block kDirectoryCategoryRequest *cagegory = [[kDirectoryCategoryRequest alloc] init];
    KBatchRequest *batch = [[KBatchRequest alloc] initWithRequestArray:@[request, cagegory]];
    [batch startWithCompletionBlockWithSuccess:^(KBatchRequest * _Nonnull batchRequest) {
        KBannersData* data = [KBannersData modelWithJSON:request.responseData];
        KDirectoryCategoryModel *model = [KDirectoryCategoryModel modelWithJSON:cagegory.responseData];
        if (data.statusCode == 200) {
            NSMutableArray* urls = [NSMutableArray array];
            if (data.bannerViews.count > 0) {
                for (KBanerModel* banner in data.bannerViews) {
                    if ([banner.imageUrl isNotBlank]) {
                        [urls addObject:[KGetImageURL stringByAppendingString:banner.imageUrl]];
                        [weakSelf.data addObject:banner];
                    }
                }
                [weakSelf.headView setImageURLStringsGroup:urls];
            }
        }else{
            [weakSelf showErrorText:data.msg errCode:data.statusCode];
        }
        
        if (model.statusCode == 200) {
            if (model.cateViews.count > 0) {
                for (KCateViews* cateview in model.cateViews) {
                    [weakSelf.items addObject:cateview];
                }
                [weakSelf.collectionView reloadData];
            }
        } else {
            [weakSelf showErrorText:model.msg errCode:data.statusCode];
        }
        [weakSelf hideHUD];
        
    } failure:^(KBatchRequest * _Nonnull batchRequest) {
        [weakSelf hideHUD];
        [weakSelf showError:batchRequest.failedRequest.error];
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - UITableViewDelegate/DataSource
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.items.count;
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    KCateViews *cateview = self.items[indexPath.row];
    HomeItemCell* cell = [collectionView dequeueReusableCellWithReuseIdentifier:[HomeItemCell className] forIndexPath:indexPath];
    __weak typeof(cell) weakCell = cell;
    
    if (cateview.imageUrl == nil || [cateview.imageUrl isEqualToString:@""]) {
        cell.backView.image = [UIImage imageNamed:@"placeholder"];
    } else {
        [cell.backView sd_setImageWithURL:cateview.imageUrl ? [NSURL URLWithString:[KGetImageURL stringByAppendingString:cateview.imageUrl]] : nil completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
            if (error) {
                weakCell.backView.image = [UIImage imageNamed:@"placeholder"];
            } else {
                CGFloat width = kScreenWidth/2-15;
                weakCell.backView.image = [image imageByResizeToSize:CGSizeMake(width, width)];
            }
        }];
    }
    
    if (cateview.url == nil || [cateview.url isEqualToString:@""]) {
        cell.itemView.image = [UIImage imageNamed:@"LinkTime"];
    } else {
        [cell.itemView sd_setImageWithURL:[NSURL URLWithString:[KGetImageURL stringByAppendingString:cateview.url]] completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
            if (error) {
                weakCell.itemView.image = [UIImage imageNamed:@"LinkTime"];
            } else {
                CGFloat width = kScreenWidth/2-15;
                weakCell.itemView.image = [image imageByResizeToSize:CGSizeMake(width, width)];
            }
        }];
    }
    cell.titleLb.text = cateview.name;
    return cell;
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    KCateViews *cateview = self.items[indexPath.row];
    HJDirectorySubViewController * vc = [HJDirectorySubViewController new];
    vc.title = cateview.name;
    vc.key = cateview.id;
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - LazyLoad
-(SDCycleScrollView *)headView
{
    if (!_headView) {
        _headView = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenWidth*0.5) shouldInfiniteLoop:YES imageNamesGroup:@[@"placeholder"]];
        _headView.pageControlDotSize = CGSizeMake(10, 10);
        _headView.backgroundColor = kWhiteColor;
        _headView.pageDotColor = kWhiteColor;
        _headView.currentPageDotColor = kYellowColor;
        _headView.autoScrollTimeInterval = 3.5;
        _headView.delegate = self;
        [self.view addSubview:_headView];
    }
    return _headView;
}

-(UICollectionView *)collectionView
{
    if (!_collectionView) {
        UICollectionViewFlowLayout* layout = [[UICollectionViewFlowLayout alloc] init];
        CGFloat width = kScreenWidth/2-15;
        layout.itemSize = CGSizeMake(width, width);
        layout.minimumLineSpacing = 10;
        layout.minimumInteritemSpacing = 10;
        layout.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10);
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(self.headView.frame), kScreenWidth, kScreenHeight-CGRectGetHeight(self.headView.frame)-64-49) collectionViewLayout:layout];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.showsVerticalScrollIndicator = NO;
        [self.view addSubview:_collectionView];
    }
    return _collectionView;
}
#pragma mark -- SDCycleScrollViewDelegate
/** 点击图片回调 */
- (void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didSelectItemAtIndex:(NSInteger)index
{
    if (self.data.count == 0) return;
    KBanerModel* model = self.data[index];
    KWebViewController * vc = [KWebViewController new];
    vc.requestUrl = model.url;
    [self.navigationController pushViewController:vc animated:YES];
}
@end
